package com.hello.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hello.common.core.constant.UserConstants;
import com.hello.common.core.exception.ServiceException;
import com.hello.common.core.utils.StringUtils;
import com.hello.common.security.utils.DictUtils;
import com.hello.system.api.dto.SysDictDataDTO;
import com.hello.system.api.dto.SysDictTypeDTO;
import com.hello.system.domain.SysDictData;
import com.hello.system.domain.SysDictType;
import com.hello.system.mapper.SysDictDataMapper;
import com.hello.system.mapper.SysDictTypeMapper;
import com.hello.system.service.ISysDictTypeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 字典 业务层处理
 * 
 * @author hello
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper, SysDictType> implements ISysDictTypeService
{
    private final SysDictDataMapper dictDataMapper;
    
    /**
     * 将SysDictData列表转换为SysDictDataDTO列表
     */
    private List<SysDictDataDTO> convertToDTO(List<SysDictData> dictDataList) {
        if (dictDataList == null) {
            return new ArrayList<>();
        }
        return dictDataList.stream().map(this::convertToDTO).collect(Collectors.toList());
    }
    
    /**
     * 将SysDictData转换为SysDictDataDTO
     */
    private SysDictDataDTO convertToDTO(SysDictData dictData) {
        if (dictData == null) {
            return null;
        }
        SysDictDataDTO dto = new SysDictDataDTO();
        BeanUtils.copyProperties(dictData, dto);
        return dto;
    }
    
    /**
     * 将SysDictDataDTO列表转换为SysDictData列表
     */
    private List<SysDictData> convertToEntity(List<SysDictDataDTO> dtoList) {
        if (dtoList == null) {
            return new ArrayList<>();
        }
        return dtoList.stream().map(this::convertToEntity).collect(Collectors.toList());
    }
    
    /**
     * 将SysDictDataDTO转换为SysDictData
     */
    private SysDictData convertToEntity(SysDictDataDTO dto) {
        if (dto == null) {
            return null;
        }
        SysDictData entity = new SysDictData();
        BeanUtils.copyProperties(dto, entity);
        return entity;
    }
    
    /**
     * 将SysDictType转换为SysDictTypeDTO
     */
    private SysDictTypeDTO convertToDTO(SysDictType type) {
        if (type == null) {
            return null;
        }
        SysDictTypeDTO dto = new SysDictTypeDTO();
        BeanUtils.copyProperties(type, dto);
        return dto;
    }
    
    /**
     * 将SysDictTypeDTO转换为SysDictType
     */
    private SysDictType convertToEntity(SysDictTypeDTO dto) {
        if (dto == null) {
            return null;
        }
        SysDictType entity = new SysDictType();
        BeanUtils.copyProperties(dto, entity);
        return entity;
    }

    /**
     * 项目启动时，初始化字典到缓存
     */
    @PostConstruct
    public void init()
    {
        loadingDictCache();
    }

    /**
     * 根据条件分页查询字典类型
     * 
     * @param dictType 字典类型信息
     * @return 字典类型集合信息
     */
    @Override
    public List<SysDictType> selectDictTypeList(SysDictType dictType)
    {
        return baseMapper.selectDictTypeList(dictType);
    }

    /**
     * 根据所有字典类型
     * 
     * @return 字典类型集合信息
     */
    @Override
    public List<SysDictType> selectDictTypeAll()
    {
        return baseMapper.selectDictTypeAll();
    }

    /**
     * 根据字典类型查询字典数据
     * 
     * @param dictType 字典类型
     * @return 字典数据集合信息
     */
    @Override
    public List<SysDictData> selectDictDataByType(String dictType)
    {
        List<SysDictDataDTO> dictDatas = DictUtils.getDictCache(dictType);
        if (StringUtils.isNotEmpty(dictDatas))
        {
            return convertToEntity(dictDatas);
        }
        List<SysDictData> dictDataEntities = dictDataMapper.selectDictDataByType(dictType);
        if (StringUtils.isNotEmpty(dictDataEntities))
        {
            DictUtils.setDictCache(dictType, convertToDTO(dictDataEntities));
            return dictDataEntities;
        }
        return null;
    }

    /**
     * 根据字典类型ID查询信息
     * 
     * @param dictId 字典类型ID
     * @return 字典类型
     */
    @Override
    public SysDictType selectDictTypeById(Long dictId)
    {
        return baseMapper.selectDictTypeById(dictId);
    }

    /**
     * 根据字典类型查询信息
     * 
     * @param dictType 字典类型
     * @return 字典类型
     */
    @Override
    public SysDictType selectDictTypeByType(String dictType)
    {
        return baseMapper.selectDictTypeByType(dictType);
    }

    /**
     * 批量删除字典类型信息
     * 
     * @param dictIds 需要删除的字典ID
     */
    @Override
    public void deleteDictTypeByIds(Long[] dictIds)
    {
        for (Long dictId : dictIds)
        {
            SysDictType dictType = selectDictTypeById(dictId);
            if (dictDataMapper.countDictDataByType(dictType.getDictType()) > 0)
            {
                throw new ServiceException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
            }
            baseMapper.deleteDictTypeById(dictId);
            DictUtils.removeDictCache(dictType.getDictType());
        }
    }

    /**
     * 加载字典缓存数据
     */
    @Override
    public void loadingDictCache()
    {
        SysDictData dictData = new SysDictData();
        dictData.setStatus("0");
        Map<String, List<SysDictData>> dictDataMap = dictDataMapper.selectDictDataList(dictData).stream().collect(Collectors.groupingBy(SysDictData::getDictType));
        for (Map.Entry<String, List<SysDictData>> entry : dictDataMap.entrySet())
        {
            DictUtils.setDictCache(entry.getKey(), convertToDTO(entry.getValue().stream().sorted(Comparator.comparing(SysDictData::getDictSort)).collect(Collectors.toList())));
        }
    }

    /**
     * 清空字典缓存数据
     */
    @Override
    public void clearDictCache()
    {
        DictUtils.clearDictCache();
    }

    /**
     * 重置字典缓存数据
     */
    @Override
    public void resetDictCache()
    {
        clearDictCache();
        loadingDictCache();
    }

    /**
     * 新增保存字典类型信息
     * 
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    public int insertDictType(SysDictType dict)
    {
        int row = baseMapper.insertDictType(dict);
        if (row > 0)
        {
            DictUtils.setDictCache(dict.getDictType(), null);
        }
        return row;
    }

    /**
     * 修改保存字典类型信息
     * 
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDictType(SysDictType dict)
    {
        SysDictType oldDict = baseMapper.selectDictTypeById(dict.getDictId());
        dictDataMapper.updateDictDataType(oldDict.getDictType(), dict.getDictType());
        int row = baseMapper.updateDictType(dict);
        if (row > 0)
        {
            List<SysDictData> dictDatas = dictDataMapper.selectDictDataByType(dict.getDictType());
            DictUtils.setDictCache(dict.getDictType(), convertToDTO(dictDatas));
        }
        return row;
    }

    /**
     * 校验字典类型称是否唯一
     * 
     * @param dict 字典类型
     * @return 结果
     */
    @Override
    public boolean checkDictTypeUnique(SysDictType dict)
    {
        Long dictId = StringUtils.isNull(dict.getDictId()) ? -1L : dict.getDictId();
        SysDictType dictType = baseMapper.checkDictTypeUnique(dict.getDictType());
        if (StringUtils.isNotNull(dictType) && dictType.getDictId().longValue() != dictId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }
}
